package org.ndx.jsg.output.freemarker;

import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;

public class Utils {

	public static String[] split(String relativePath) {
		Collection<String> tokens = splitAsList(relativePath);
		return tokens.toArray(new String[tokens.size()]);
	}

	private static List<String> splitAsList(String relativePath) {
		List<String> tokens = new LinkedList<String>();
		StringTokenizer tokenizer = new StringTokenizer(relativePath,
				File.separator);
		while (tokenizer.hasMoreElements()) {
			String temp = tokenizer.nextToken();
			if (temp.length() > 0)
				tokens.add(temp);
		}
		return tokens;
	}

	/**
	 * Compress a path from one file to another
	 * 
	 * @param relativePath
	 * @param relativeUrl
	 * @return
	 */
	public static String compress(String relativePath, String relativeUrl) {
		List<String> relativeIn = Utils.splitAsList(relativePath);
		List<String> relativeOut = Utils.splitAsList(relativeUrl);
		return merge(relativeIn, relativeOut, "");
	}

	public static String merge(List<String> relativeIn,
			List<String> relativeOut, String prefix) {
		if (relativeIn.size() == 0)
			return prefix + join(relativeOut, File.separator);
		if (relativeOut.size() == 0) {
			Collections.fill(relativeIn, "..");
			return prefix + join(relativeIn, File.separator);
		}
		String in = relativeIn.get(0);
		String out = relativeOut.get(0);
		if (in.equals(out)) {
			relativeIn.remove(0);
			relativeOut.remove(0);
			return merge(relativeIn, relativeOut, prefix);
		} else {
			Collections.fill(relativeIn, "..");
			return prefix + join(relativeIn, File.separator) + File.separator
					+ join(relativeOut, File.separator);
		}
	}

	/**
	 * Join string using given separator
	 * 
	 * @param relativeOut
	 * @param separator
	 * @return
	 */
	public static String join(List<String> relativeOut, String separator) {
		StringBuilder sout = new StringBuilder();
		Iterator<String> iterator = relativeOut.iterator();
		while (iterator.hasNext()) {
			sout.append(iterator.next());
			if (iterator.hasNext()) {
				sout.append(separator);
			}
		}
		return sout.toString();
	}
}
